package 面试题;

public class 杨辉三角 {
    //递归
    public int[][] helper_rec(int deep) {
        int[][] a = new int[deep][];
        for (int i = 0; i < deep; i++) {
            a[i] = new int[i + 1];
        }
        for (int i = 0; i < deep; i++) {
            for (int j = 0; j <= i; j++) {
                a[i][j] = rec(i, j);
            }
        }
        return a;
    }

    private int rec(int i, int j) {
        if (j == 0 || j == i) {
            return 1;
        }
        return rec(i - 1, j) + rec(i - 1, j - 1);
    }

    public static void main(String[] args) {
        杨辉三角 t = new 杨辉三角();
        int deep = 10;
        int[][] res = t.helper_rec(deep);
        for (int i = 0; i < deep; i++) {
            //等边三角就加上这两行，直角三角则去掉这两行
            int space = deep - i - 1;
            for (int j = 0; j < space; j++) {
                System.out.print(" ");
            }

            for (int j = 0; j < res[i].length; j++) {
                System.out.print(res[i][j] + " ");
            }
            System.out.println();
        }
    }

    //===========================

    //非递归
    public int[][] helper(int deep) {
        int[][] a = new int[deep][];
        for (int i = 0; i < deep; i++) {
            a[i] = new int[i + 1];
        }
        for (int i = 0; i < deep; i++) {
            a[i][0] = 1;
            a[i][a[i].length - 1] = 1;
        }
        for (int i = 2; i < deep; i++) {
            for (int j = 1; j < i; j++) {
                a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
            }
        }
        return a;
    }

    public static void main2(String[] args) {
        杨辉三角 t = new 杨辉三角();
        int deep = 10;
        int[][] res = t.helper(deep);
        for (int i = 0; i < deep; i++) {
            //等边三角就加上这两行，直角三角则去掉这两行
            int space = deep - i - 1;
            for (int j = 0; j < space; j++) {
                System.out.print(" ");
            }

            for (int j = 0; j < res[i].length; j++) {
                System.out.print(res[i][j] + " ");
            }
            System.out.println();
        }
    }
}
